<?php

/*------------------------------------------------
*
*   Explay Engine Content Management System.
*   Copyright © 2008 Golovdinov Alexander.
*
*-------------------------------------------------
*
*   Official site: wwww.alex-home.spb.ru/explay.html
*   Contact e-mail: golovdinov@gmail.com
*
*   GNU General Public License original source:
*   http://www.gnu.org/licenses/gpl-3.0.html
*
------------------------------------------------*/

if (!defined ('EXPLAY')) exit;

$USER = $db->fetch_array ($db->query ("SELECT * FROM ".DB_PEREFIX."_users WHERE user_id = '".$GLOBAL_USER['user_id']."'"));

$avatar = (file_exists ($_SERVER['DOCUMENT_ROOT'].'/images/avatars/'.User::$properties['user_id'].'.jpg'))
				? '/images/avatars/'.User::$properties['user_id'].'.jpg'
				: '/images/avatars/noavatar.jpg';

if ($USER['allow_comments'] == 'on') $allow_comments = 'checked';

$file = file ($_SERVER['DOCUMENT_ROOT'].'/modules/auth/admin/fields_options.txt');
$field = array ();

foreach ($file as $f) {
	$fld = explode ('|', $f);
	//print "{$fld[0]}|{$fld[1]}|{$fld[2]}|{$fld[3]}|{$fld[4]}|{$fld[5]}<br>";
	(isset($fld[2])) ? $field[$fld[0]] = $fld : $field[$fld[0]] = trim($fld[1]);
}



/*
 *
 *
 * Форма редактирования профиля
 *
 *
*/

$form = "\n<form name=\"regist\" action=\"/edit_profile/\" method=\"POST\" enctype=\"multipart/form-data\">
<table cellspacing=\"0\" cellpadding=\"4\" width=\"100%\">";

if ($field['avatar'] == 'on') {
	$form .= "<tr>
		<td width=\"20%\" valign=\"bottom\" align=\"right\" width=\"35%\">Аватар:</td>
		<td><img src=\"$avatar\" title=\"{$USER['user_name']}\" alt=\"{$USER['user_name']}\" /></td>
	</tr>";
}

$form .= "<tr>
		<td width=\"20%\" align=\"right\">Имя<span style=\"color:red;\"><sup>*</sup></span>:</td>
		<td><input style=\"width:60%\" type=\"text\" name=\"name\" maxlength=\"30\" value=\"{$USER['user_name']}\" /></td>
	</tr>
	<tr>
		<td align=\"right\">E-mail<span style=\"color:red;\"><sup>*</sup></span>:</td>
		<td><input style=\"width:60%\" type=\"text\" name=\"email\" maxlength=\"30\" value=\"{$USER['user_email']}\" /></td>
	</tr>";

// Дополнительные зарезервированные поля
if ($field['gender'] == 'on') {
	
	$n = '';
	$m = '';
	$f = '';
	
	switch ($USER['gender']) {		
		case 0:
			$n = 'selected';
			break;
		case 1:
			$m = 'selected';
			break;
		case 2:
			$f = 'selected';
			break;
	}
	
	$form .= "\n\t<tr>
		<td align=\"right\">Пол:</td>
		<td>
			<select name=\"gender\">
				<option value=\"0\" $n>Неопределенный</option>
				<option value=\"1\" $m>Мужской</option>
				<option value=\"2\" $f>Женский</option>
			</select>
		</td>
	</tr>";
}

if ($field['birthdate'] == 'on') {
	
	$date = array(
		date('j', $USER['birthdate']),
		date('n', $USER['birthdate']),
		date('Y', $USER['birthdate'])
	);
	
	// Шли дни...
	$days = '';
	for ($i=1; $i<=31; $i++) {
		($date[0] == $i && !empty($USER['birthdate']))
			? $days .= "\r\n\t\t\t\t<option selected>$i</option>"
			: $days .= "\r\n\t\t\t\t<option>$i</option>";
	}
	
	// Месяцы...
	$mounth_arr = array ('','Январь','Февраль','Март','Апрель','Май','Июнь','Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь');
	$mounth = '';
	for ($i=1; $i<=12; $i++) {
		($date[1] == $i && !empty($USER['birthdate']))
			? $mounth .= "\r\n\t\t\t\t<option value=\"$i\" selected>".$mounth_arr[$i]."</option>"
			: $mounth .= "\r\n\t\t\t\t<option value=\"$i\">".$mounth_arr[$i]."</option>";
	}
	
	// Годы...
	$years = '';
	for ($i=date('Y'); $i>=1970; $i--) {
		($date[2] == $i && !empty($USER['birthdate']))
			? $years .= "\r\n\t\t\t\t<option selected>$i</option>"
			: $years .= "\r\n\t\t\t\t<option>$i</option>";
	}
	
	// А он все читал исходники...
	$form .= "\n\t<tr>
		<td align=\"right\">Дата рождения:</td>
		<td>
			<select name=\"day\">
				<option value=\"0\">день</option>$days
			</select>
			<select name=\"mounth\">
				<option value=\"0\">месяц</option>$mounth
			</select>
			<select name=\"year\">
				<option value=\"0\">год</option>$years
			</select>
		</td>
	</tr>";
}

if ($field['icq'] == 'on') {
	$form .= "\n\t<tr>
		<td align=\"right\">ICQ:</td>
		<td><input style=\"width:60%\" type=\"text\" name=\"icq\" maxlength=\"15\" value=\"{$USER['user_icq']}\" /></td>
	</tr>";
}
if ($field['http'] == 'on') {
	$form .= "\n\t<tr>
		<td align=\"right\" valign=\"top\">Сайт:</td>
		<td>
			<input style=\"width:60%\" type=\"text\" name=\"http\" maxlength=\"40\" value=\"{$USER['user_http']}\" />
			<br /><span class=\"help\">Например, http://www.myhomesite.com</span>
		</td>
	</tr>";
}
if ($field['avatar'] == 'on') {
	 $form .= "\n\t<tr>
		<td align=\"right\" valign=\"top\">Аватар:</td>
		<td><input type=\"file\" name=\"image\" /></td>
	</tr>";
	
	if ($avatar != '/images/avatars/noavatar.gif') {
		$form .= "\n\t<tr>
			<td align=\"right\">Удалить аватар:</td>
			<td><input type=\"checkbox\" name=\"d_avatar\" value=\"true\" /></td>
		</tr>\n";	
	}
}
if ($field['comments'] == 'on') {
	$form .= "\n\t<tr>
		<td align=\"right\">Разрешить оставлять комментарии к профилю:</td>
		<td valign=\"top\"><input type=\"checkbox\" name=\"allow_comments\" value=\"on\" $allow_comments /></td>
	</tr>";
}

// Дополнимтельные поля

// 0 - name
// 1 - status
// 2 - type
// 3 - value (not for all)
// 4 - label
// 5 - important

for ($i=1; $i<=9; $i++) {
	if (trim($field['ad'.$i][1]) == 'on') {
		$GLOBAL_USER['additional'.$i] = replace_symbols ($GLOBAL_USER['additional'.$i]);
		$GLOBAL_USER['additional'.$i] = str_replace ('&', '&amp;', $GLOBAL_USER['additional'.$i]);
		
		$form .= "\n\t<tr>\n\t\t<td align=\"right\" valign=\"top\">{$field['ad'.$i][4]}";
		if (trim($field['ad'.$i][5]) == 'on')
			$form .= "<span style=\"color:red;\"><sup>*</sup></span>";
		$form .= ":</td>\n\t\t<td valign=\"top\">";
		
		
		
		if ($field['ad'.$i][2] == 'text') 
			$form .= "\n\t\t\t<input type=\"text\" name=\"ad$i\" style=\"width:180px\" value=\"{$GLOBAL_USER['additional'.$i]}\" />";
		
		elseif ($field['ad'.$i][2] == "checkbox")
			($GLOBAL_USER['additional$i'] == '1')
				? $form .= "\n\t\t\t<input type=\"checkbox\" name=\"ad$i\" value=\"1\" checked />"
				: $form .= "\n\t\t\t<input type=\"checkbox\" name=\"ad$i\" value=\"1\" />";
		
		elseif ($field['ad'.$i][2] == 'textarea')
			$form .= "\n\t\t\t<textarea name=\"ad$i\" rows=\"10\" style=\"width:90%;\">{$GLOBAL_USER['additional'.$i]}</textarea>";
		
		elseif ($field['ad'.$i][2] == 'select') {
			$form .= "\n\t\t\t<select name=\"ad$i\">";
			$values = explode ("<br>", $field['ad'.$i][3]);
			foreach ($values as $value) {
				($value == $GLOBAL_USER['additional'.$i])
					? $form .= "\n\t\t\t\t<option value=\"$value\" selected>$value</option>"
					: $form .= "\n\t\t\t\t<option value=\"$value\">$value</option>"; 
			}
			$form .= "\n\t\t\t</select>";
		}
		
		elseif ($field['ad'.$i][2] == 'radio') {
			$values = explode ('<br>', $field['ad'.$i][3]);
			foreach ($values as $value) {
				($value == $GLOBAL_USER['additional'.$i])
					? $form .= "\n\t\t\t<input type=\"radio\" name=\"ad$i\" value=\"$value\" checked /> $value<br />"
					: $form .= "\n\t\t\t<input type=\"radio\" name=\"ad$i\" value=\"$value\" /> $value<br />";
			}
		}
		
		$form .= "\n\t\t</td>\n\t</tr>";
	}
}

	$form .= "\n<tr>
		<td colspan=\"2\" align=\"center\">
			<input type=\"submit\" name=\"save\" value=\"Сохранить\" style=\"width:200px\" /><p />
			<small><span style=\"color:red;\">*</span> &mdash; обязательные для заполнения поля</small>
		</td>
	</tr>
</table></form>";	


// We trust the god
if (isset($_POST['save'])) {
	
	$uid = User::$properties['user_id'];
	
	$nname = strip_tags($_POST['name']);

	$bad = array ("`","~","@","#","$","%","^","&","*","-","=","+","{","}",">","<",",","?","/","|");
	$repl = array ("","","","","","","","","","","","","","","","","","","","");
	$nname = str_replace ($bad, $repl, $nname);
	
	
	$gender = intval($_POST['gender']);
	$nemail = strip_tags($_POST['email']);
	$nview = strip_tags($_POST['vemail']);
	$nicq = strip_tags(trim($_POST['icq']));
	$nicq = str_replace ('-', '', $nicq);
	$nicq = str_replace (' ', '', $nicq);
	$nhttp = strip_tags($_POST['http']);
	$nhttp = str_replace ('http://', '', $nhttp);
	(isset ($_POST['allow_comments'])) ? $allow_comments = 'on' : $allow_comments = 'off';
	
	$error = '';	
	
	//==========================================================
	// 0 - name
	// 1 - status
	// 2 - type
	// 3 - value (not for all)
	// 4 - label
	// 5 - important
	$str = '';
	for ($i=1; $i<=9; $i++) {
		$ad = '';
		if (trim($field['ad'.$i][1]) == 'on') {
			if ($field['ad'.$i][5] == 'on' && (!isset($_POST['ad'.$i]) || strip_tags(trim($_POST['ad'.$i])) == ''))
				$error .= '<li>Не заполнено обязательное поле '.$field['ad'.$i][4].'!';
			else
				$ad = strip_tags(trim($_POST['ad'.$i]));
		}
		$str .= " , additional$i = '$ad' ";
	}
	//==========================================================
	
	$check_email = $db->query ("SELECT user_email FROM ".DB_PEREFIX."_users WHERE user_email = '$nemail' AND user_id != '".$GLOBAL_USER['user_id']."'");
	$check_name = $db->query ("SELECT * FROM ".DB_PEREFIX."_users WHERE user_name = '$nname' AND user_id != '".$GLOBAL_USER['user_id']."'");
		
	if (mb_strlen($nname) < $SITE['user_name'] || mb_strlen($nname) > 30) $error .= '<li>Имя должно быть от '.$SITE['user_name'].' до 16 символов!';
	
	if ($db->num_rows($check_name) > 0) $error .= '<li>Пользователь с таким именем уже существует!';
	if ($db->num_rows($check_email) > 0) $error .= '<li>Пользователь с таким e-mail уже существует!';
		
	if (!eregi("^[a-z0-9\._-]+@[a-z0-9\._-]+\.[a-z]{2,4}\$",$nemail)) $error .= '<li>Неправильный формат e-mail!';
			
	
	// Новый аватар
	if ($_FILES['image']['name'] != '') {
		if (copy($_FILES['image']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/include/cache/'.$_FILES['image']['name']) && eregi('[A-Za-z0-9]\.(jpeg|jpg|gif|png|bmp|JPEG|JPG|GIF|PNG|BMP)', $_FILES['image']['name'])) {
			
			include $_SERVER['DOCUMENT_ROOT'].'/engine/image.class.php';
			
			try {
				$image = new imageResize (
						$_SERVER['DOCUMENT_ROOT'].'/include/cache/'.$_FILES['image']['name'],
						$uid,
						'images/avatars',
						array($SITE['max_avatar'], $SITE['max_avatar']),
						false,
						80
					);
					
				$image->resize ();
			}
			catch (Exception $e) {
				$error .= '<li>'.$e->getMessage();
			}
			
		}				
		else $error .= '<li>Ошибка загрузки изоображения!';
		
		if (file_exists ($_SERVER['DOCUMENT_ROOT'].'/include/cache/'.$_FILES['image']['name'])) {
			unlink ($_SERVER['DOCUMENT_ROOT'].'/include/cache/'.$_FILES['image']['name']);
		}
	}
	
	// Если указаны все поля в дате рождения, то преобразуем ее в строку
	if (!empty ($_POST['day']) && !empty ($_POST['mounth']) && !empty ($_POST['year'])) {
		
		if (!$birthdate = strtotime (intval($_POST['day']).'.'.intval($_POST['mounth']).'.'.intval($_POST['year'])))
			$error .= 'Неправильный формат даты!';
	}
	else $birthdate = 0;
		
	
	// Удаляем аватар	
	if (isset ($_POST['d_avatar'])) {
		
		if (file_exists ($_SERVER['DOCUMENT_ROOT'].'/images/avatars/'.$uid.'.jpg')) unlink ($_SERVER['DOCUMENT_ROOT'].'/images/avatars/'.$uid.'.jpg');
		if (file_exists ($_SERVER['DOCUMENT_ROOT'].'/images/avatars/'.$uid.'_small.jpg')) unlink ($_SERVER['DOCUMENT_ROOT'].'/images/avatars/'.$uid.'_small.jpg');
		
		site_message ('Аватар удален');
	}

	// Если ошибок нет, то записываем изменения	
	if ($error == '') {
		$db->query("UPDATE ".DB_PEREFIX."_users SET
			user_name = '$nname',
			user_email = '$nemail',
			user_icq = '$nicq',
			user_http = '$nhttp',
			allow_comments = '$allow_comments',
			gender = '$gender',
			birthdate = '$birthdate'
			$str WHERE user_id = '".$GLOBAL_USER['user_id']."'");
			
		site_message ("Профиль сохранен!");
		$GLOBAL_USER = $db->fetch_array ($db->query ("SELECT * FROM ".DB_PEREFIX."_users WHERE user_id = '".$GLOBAL_USER['user_id']."'"));
	
	} else {
		
		site_error ($error);
		if ($_FILES['image']['name'] != '') {
			if (file_exists($_SERVER['DOCUMENT_ROOT'].'/images/avatars/'.User::$properties['user_id'].'.jpg'))
				unlink ($_SERVER['DOCUMENT_ROOT'].'/images/avatars/'.User::$properties['user_id'].'.jpg');
		}
			
	}

}


// Сохранение пароля
if (isset($_POST['change_password'])) {
	if ($_POST['old_pass'] != '' && $_POST['new_pass'] != '' && $_POST['repeat_pass'] != '') {
		$old = $_POST['old_pass'];
		$new = $_POST['new_pass'];
		$repeat = $_POST['repeat_pass'];
		
		$error = '';
		
		$check = $db->num_rows ($db->query ("SELECT * FROM ".DB_PEREFIX."_users WHERE user_id = ".$GLOBAL_USER['user_id']." AND user_password = '".expl_hash($old)."'"));
		
		if ($check == 0) $error .= '<li>Неправильный старый пароль!';
		if ($new != $repeat) $error .= '<li>Пароли не совпадают!';
		if ($new == $old) $error .= '<li>Какой идиот будет менять старый пароль на новый, когда они одинаковые!';
		if (mb_strlen($new) < $SITE['user_name'] || mb_strlen($new) > 16) $error .= '<li>Пароль должен быть не короче '.$SITE['user_name'].' и не длинее 16 символов!';
		
		if ($error == '') {
			$new = expl_hash ($_POST['new_pass']);
			
			$db->query ("UPDATE ".DB_PEREFIX."_users SET user_password = '$new' WHERE user_id = ".$GLOBAL_USER['user_id']);
			site_message ('Новый пароль сохранен.<br /><input type="button" value="Вход под новым паролем" onclick="document.location.href=\'/login.html\'" />');
		}
		else site_error ('Обновление пароля:'.$error);
		
				
		
	}
	else site_error ('Обновление пароля: Не заполнено одно из полей!');
}

print_reg ();
password_form ();

if ($_FILES['image']['name'] != '') {
	if (file_exists ($_SERVER['DOCUMENT_ROOT'].'/include/cache/'.$_FILES['image']['name']))
		unlink ($_SERVER['DOCUMENT_ROOT'].'/include/cache/'.$_FILES['image']['name']);
}








function password_form () {
	global $SITE;
	
	$form = "<form action=\"edit_profile\" method=\"post\">
<table cellspacing=\"0\" cellpadding=\"4\" width=\"100%\">
	<tr>
		<td width=\"20%\" align=\"right\">Старый пароль:</td>
		<td><input style=\"width:60%\" type=\"password\" name=\"old_pass\" maxlength=\"15\" value=\"\" /></td>
	</tr>
	<tr>
		<td valign=\"top\" align=\"right\">Новый пароль:</td>
		<td>
			<input style=\"width:60%\" type=\"password\" name=\"new_pass\" maxlength=\"15\" value=\"\" />
			<br /><span class=\"help\">Пароль должен быть не короче ".$SITE['user_name']." символов.</span>
		</td>
	</tr>
	<tr>
		<td align=\"right\">Повторите пароль:</td>
		<td><input style=\"width:60%\" type=\"password\" name=\"repeat_pass\" maxlength=\"15\" value=\"\" /></td>
	</tr>
	<tr>
		<td colspan=\"2\" align=\"center\"><input type=\"submit\" name=\"change_password\" value=\"Сохранить пароль\" /></td>
	</tr>
</table>
</form>";
	
	past_table ('Смена пароля', $form);
	
}




function print_reg () {
	global $form, $GLOBAL_USER;
	past_table ('Редактирование профиля '.$GLOBAL_USER['user_name'], $form);
}
